<template>
  <div class="details-box">
    <h4 class="title">{{ data.title }}</h4>
    <div class="time">
      <span>发布时间：{{ data.createTime }}</span>
      <span style="margin-left: 50px">最近修改时间：{{ data.updateTime }}</span>
      <div class="item-style">
        <el-button
          type="danger"
          @click="addShopcartClick"
          v-if="data.type == 'goods'"
          >加入购物车</el-button
        >
        <el-popover placement="right" width="320" trigger="hover">
          <div>
            <div class="item-sales">
              买家姓名：<span class="sales-text">{{ data.ownName }}</span>
            </div>
            <div class="item-sales">
              买家地址：<span class="sales-text">{{ data.address }}</span>
            </div>
            <div class="item-sales">
              更新时间：<span class="sales-text">{{
                data.updateTime | formatTimer
              }}</span>
            </div>
          </div>
          <div
            style="
              color: #fc7373;
              margin-left: 50px;
              cursor: pointer;
              display: flex;
            "
            slot="reference"
            @click="changeInfo"
            v-show="data.type == 'needs'"
          >
            <div
              style="
                margin-right: 10px;
                color: #fff;
                font-weight: bold;
                background: #fc7373;
                width: 20px;
                height: 20px;
                border-radius: 10px;
                line-height: 20px;
                text-align: center;
              "
            >
              !
            </div>
            买家信息
          </div>
        </el-popover>
      </div>
    </div>
    <img
      :src="$store.state.imgShowRoad + '/file/' + data.picture"
      v-show="data.picture"
      alt=""
    />
    <div class="info">
      <div class="content" :title="data.content">{{ data.content }}</div>
    </div>
    <div
      v-show="this.showEchart"
      ref="myChart"
      style="
        width: 800px;
        height: 600px;
        margin: -200px auto 0;
        border: 1px solid #aaa;
        box-sizing: content-box;
      "
    ></div>
    <div v-show="!this.showEchart">
      <span><h1>暂无往期数据</h1></span>
    </div>
  </div>
</template>

<script>
import { addOrderToCart } from "../api/cart";
import { selectOrderById } from "../api/order";
import ChangeMessage from "../components/ChangeMessage.vue";
import { selectUserByUsername } from "../api/user";
import { getCrops, doPredict } from "../api/predict";
import * as echarts from "echarts";

export default {
  data() {
    return {
      data: [],
      ownerInfo: {},
      userGoods: [],
      updateGoodInfo: {},
      updateUserData: {},
      predictForm: {
        crop: "",
      },
      showEchart: false,
    };
  },
  filters: {
    formatTimer: function (value) {
      let date = new Date(value);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      return y + "-" + MM + "-" + d + " ";
    },
  },
  components: { ChangeMessage },
  props: {
    ctype: {
      type: String,
    },
    cdesciibe: {
      type: String,
    },
  },
  methods: {
    addShopcartClick() {
      addOrderToCart({
        order_id: this.data.orderId,
      })
        .then((res) => {
          if (res.flag == true) {
            alert(res.message);
          } else {
            alert(res.message);
          }
        })
        .catch((err) => {
          alert("添加失败,请先登录");
        });
    },
    changeInfo() {
      this.$store.commit(
        "updateChangedOrderId",
        this.$store.state.changedOrderId
      );
      selectOrderById({
        order_id: this.$store.state.changedOrderId,
      })
        .then((res) => {
          this.updateGoodInfo = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getSalesInfo() {
      selectUserByUsername({
        user_name: this.data.ownName,
      })
        .then((res) => {
          this.updateUserData = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    initPredict() {
      getCrops()
        .then((res) => {
          // 匹配到的作物
          // alert("111")
          console.log(res);
          let crop = null;
          // alert("222")
          const cropList = res.data.crop_list;
          // alert("333")
          cropList.forEach((item) => {
            if (this.data.title.indexOf(item) != -1) {
              crop = item;
            }
          });
          // 解析本页面的crop
          this.predictForm.crop = crop;
          // alert(crop)
          return doPredict({ crop: crop });
        })
        .then((res) => {
          if (res.status == 1) {
          // 展示Echarts
          console.log(res)
          this.showEchart = true;
          const datas = res.data.datas;
          let original = datas.original;
          let fitted = datas.fitted;
          let future = datas.future;
          // 绘制曲线
          this.renderChart(original, fitted, future);
          }
        });
    },
    // 绘制预测曲线
    renderNewChart(future) {
      const chart = echarts.init(this.$refs.myChart);
      console.log(future)
      let dates=Object.keys(future)
      let yValue=Object.values(future)
      let xValue = []
      dates.forEach(element => {
        const date = new Date(element);
        let aDate=(date.getMonth()+1)+'月'+date.getDate()+'日'
        xValue.push(aDate)
      });
      let option = {
        title: {
          text: `${this.predictForm.crop}作物价格变化曲线图`,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985",
            },
          },
        },
        legend: {
          data: ["价格变动曲线"],
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            data: xValue,
          },
        ],
        yAxis: [
          {
            type: "value",
          },
        ],
        series: [
          {
            name: `${this.predictForm.crop}作物价格`,
            type: "line",
            stack: "Total",
            areaStyle: {},
            emphasis: {
              focus: "series",
            },
            data: yValue,
          },
        ],
      };
      chart.setOption(option)
    },
    // 绘制预测曲线
    renderChart(original, fitted, future) {
      const chart = echarts.init(this.$refs.myChart);

      // 构造完整的x索引,以及test_predict和future的填充
      const fullIndex = Object.keys({ ...original, ...future });
      const originalValue = Object.values(original); // 不处理,索引开头对上了
      // 确定滑动窗口其实预测位置(=滑动窗口大小)
      let windowIndex = Object.keys(original).indexOf(Object.keys(fitted)[0]);
      let fittedValue = Object.values(fitted); // 不处理,索引开头对上了
      // 如果基于滑动窗口的,需要向后偏移window_size个位置
      fittedValue =
        windowIndex === 0
          ? fittedValue
          : [...Array(windowIndex).fill(null), ...fittedValue];
      const futureValue = [
        ...Array(originalValue.length).fill(null),
        ...Object.values(future),
      ]; // 处理,之前填充长度为original的Nan

      chart.setOption({
        title: {
          text: `${this.predictForm.crop}作物价格变化曲线图`,
          textStyle: {
            color: "#555",
            fontSize: 24,
          },
          x: "center",
          top: "5%",
        },
        backgroundColor: "#fff",
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            let result = `时间： ${params[0].name}<br/>`;
            params.forEach(function (item) {
              if (item.value) {
                result += `<div style="display: inline-block; width: 12px;height: 12px; margin-right: 6px; background-color: ${item.color};"></div>${item.seriesName}： ${item.value}<br/>`;
              }
            });
            return result;
          },
        },
        // 保存图片
        toolbox: {
          top: "2%",
          left: "3%",
          iconStyle: {
            borderColor: "#1890ff",
          },
          feature: {
            saveAsImage: {
              type: "png",
              name: `${this.predictForm.crop}作物价格预测曲线图`,
            },
          },
        },
        xAxis: {
          name: "日期",
          type: "category",
          nameTextStyle: {
            color: "#555",
            fontWeight: "bold",
            fontSize: 15,
          },
          axisLabel: {
            color: "#000",
          },
          data: fullIndex,
        },
        yAxis: {
          type: "value",
          boundaryGap: false,
          name: `价格/斤`,
          nameTextStyle: {
            color: "#555",
            fontWeight: "bold",
            fontSize: 15,
          },
          axisLabel: {
            color: "#000",
          },
          splitLine: {
            show: false,
          },
        },
        series: [
          { name: "往期价格", data: originalValue, type: "line", color: "blue" },
          // {
          //   name: "模型训练",
          //   data: fittedValue,
          //   type: "line",
          //   color: "yellowgreen",
          // }
          // ,
          { name: "预测价格", data: futureValue, type: "line", color: "red" },
        ],
        legend: {
          show: true,
          right: "3%",
          top: "3%",
          orient: "vertical", // 图例的布局朝向
          borderColor: "#333",
          borderWidth: 0.5,
        },
      });
    },
  },
  mounted() {
    this.$store.commit("updateActiveIndex", "3");
    // 初始化商品数据
    selectOrderById({
      order_id: this.$route.query.orderId,
    }).then((res) => {
      if (res.flag == true) {
        this.data = res.data;
        this.getSalesInfo();
        // 页面初始数据加载后,请求进行农产品价格预测
        this.initPredict();
      }
    });
  },
};
</script>

<style lang="less" scoped>
.details-box {
  width: 1100px;
  min-height: 100%;
  height: auto;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  display: flex;
  flex-direction: column;
  // align-items: center;
  img {
    width: 360px;
    height: 300px;
    margin: 50px auto 20px;
    border-radius: 6px;
  }

  .title {
    font-size: 24px;
    font-weight: bold;
    line-height: 35px;
    max-height: 70px;
    text-align: center;
    margin-bottom: 20px;
  }

  .time {
    margin-top: 5px;
    color: #999;
    display: flex;
    justify-content: flex-end;
  }

  .info {
    width: 100%;
    min-height: 300px;
    border-radius: 6px;
    padding: 10px 20px;
    margin: 0 auto;
    display: flex;
    align-content: center;
    justify-content: center;

    .content {
      min-height: 100px;
      // border: 1px dashed #f2f2f2;
      line-height: 25px;
      padding: 5px 10px;
      /*超出的部分隐藏*/
      overflow: hidden;
      /*文字用省略号替代超出的部分*/
      text-overflow: ellipsis;
      /*弹性伸缩盒子模型显示*/
      display: -webkit-box;
      /*限制在一个块元素显示文本的行数*/
      -webkit-line-clamp: 4;
      /*设置或检索伸缩盒对象的子元素排列方式*/
      -webkit-box-orient: vertical;
    }

    .item-style {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      margin-top: 5px;
    }
  }

  .item-sales {
    color: #333 !important;
    line-height: 30px;
    max-height: 30px;

    .sales-text {
      color: #666;
    }
  }
}
</style>